<template>
  <n-spin :show="updateLoading">
    <n-card size="small">
      <n-h3 class="flex flex-row justify-between items-center">
        <span>#{{ orderInfo.num }}</span>
        <n-select
          class="flex-1 ml-[10px] max-w-[200px]"
          v-model:value="ownRepairInfo.status"
          value-field="value"
          label-field="name"
          :options="repairStatusList"
          @update:value="handleChangeRepairStatus"
        />
      </n-h3>

      <div class="flex items-center">
        <n-icon><TimeOutline /></n-icon>
        <span class="ml-1">创建时间：{{ orderInfo.createTime }}</span>
      </div>
      <div class="mt-[16px]"></div>
      <n-scrollbar :style="REPAIR_INFO_CONTAINER_STYLE">
        <n-space vertical>
          <div>
            <span class="font-bold text-base">维修设备信息</span>
            <n-space vertical>
              <!-- MODEL -->
              <div>
                <div class="label-title">
                  <span>型号</span>
                </div>
                <div
                  class="label-value flex flex-row justify-between items-center"
                >
                  <span>{{ ownRepairInfo.variantName }}</span>
                  <n-button quaternary circle @click.stop="handleEditVariant">
                    <template #icon>
                      <n-icon><CreateOutline /></n-icon>
                    </template>
                  </n-button>
                </div>
              </div>
              <!-- IMEI -->
              <div>
                <div class="label-title">
                  <span>IMEI/SN</span>
                </div>
                <div
                  class="label-value flex flex-row justify-between items-center"
                >
                  <n-input-group>
                    <n-input
                      clearable
                      v-model:value="ownRepairInfo.sn"
                      placeholder="请输入IMEI/SN"
                      :disabled="!editImeiFlag"
                    />
                    <n-button @click.stop="handleClickEditSn">
                      <template #icon>
                        <n-icon>
                          <CheckmarkOutline v-if="editImeiFlag" />
                          <CreateOutline v-else />
                        </n-icon>
                      </template>
                    </n-button>
                  </n-input-group>
                </div>
              </div>
              <!-- PIN -->
              <div>
                <div class="label-title">
                  <span>解锁密码</span>
                </div>
                <div
                  class="label-value flex flex-row justify-between items-center"
                >
                  <n-input-group size="small">
                    <n-input
                      clearable
                      v-model:value="ownRepairInfo.pin"
                      placehodler="请输入解锁密码"
                      :disabled="!editPinFlag"
                    />
                    <n-button @click.stop="handleClickEditPin">
                      <template #icon>
                        <n-icon>
                          <CheckmarkOutline v-if="editPinFlag" />
                          <CreateOutline v-else />
                        </n-icon>
                      </template>
                    </n-button>
                  </n-input-group>
                </div>
              </div>
            </n-space>
          </div>
          <div>
            <div class="flex flex-row justify-between items-center">
              <span class="font-bold text-base">故障清单</span>
              <n-button quaternary circle @click.stop="handleClickAddQuestion">
                <template #icon>
                  <n-icon><AddCircleOutline /></n-icon>
                </template>
              </n-button>
            </div>
            <n-space vertical>
              <template v-if="selectedCheckList.length">
                <div
                  class="question-item"
                  v-for="checkItem in selectedCheckList"
                  :key="checkItem.id"
                >
                  <span class="font-bold leading-[28px]">
                    {{ checkItem.questionName }}
                  </span>
                  <n-popconfirm
                    @positive-click="handleRemoveQuestion(checkItem)"
                  >
                    <span>确定要移除故障吗？</span>
                    <template #trigger>
                      <n-button size="small" type="error" circle>
                        <template #icon>
                          <n-icon><TrashOutline /></n-icon>
                        </template>
                      </n-button>
                    </template>
                  </n-popconfirm>
                </div>
              </template>
              <n-empty class="pt-2" v-else />
            </n-space>
          </div>
        </n-space>
      </n-scrollbar>
      <template #action>
        <div class="flex flex-row justify-between items-center">
          <span class="font-bold text-base">维修预估报价</span>
          <span class="font-bold text-base">
            {{ currencyFormat(repairInfo.quotePrice) }}
          </span>
        </div>
      </template>
    </n-card>
  </n-spin>
  <CheckResultModal
    :title="checkResultTitle"
    :checkResultList="checkResultList"
    can-edit
    v-model:show="showCheckResult"
    @close="showCheckResult = false"
    @cancel="showCheckResult = false"
    @confirm="handleConfirmAddQuestion"
  >
    <template v-slot:name="{ checkResult }">
      {{ checkResult.questionName }}
    </template>
  </CheckResultModal>
  <ChooseVariantModal
    title="选择设备信息"
    v-model:show="showVariantModal"
    :product-id="ownRepairInfo.productId"
    @confirm="handleUpdateVariant"
    @close="showVariantModal = false"
    @cancel="showVariantModal = false"
  />
</template>
<script lang="ts" setup>
import { computed, watch, ref } from "vue";
import { get, isEmpty, cloneDeep, debounce } from "lodash-es";
import { useMessage } from "naive-ui";
import {
  AddCircleOutline,
  TimeOutline,
  CheckmarkOutline,
  CreateOutline,
  TrashOutline,
} from "@vicons/ionicons5";
import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import {
  useCheckResultModal,
  CheckResultModal,
} from "@/components/biz/checkResultModal/index.ts";
import {
  changeRepairStatus,
  updateCheckResult,
  updateCheckResultBatch,
  updateRepairVariant,
  updatePin,
  updateSn,
} from "@/api/repair/repair.api";
import { ChooseVariantModal } from "@/components/biz/chooseVariantModal/index.ts";
import { repairStatusList } from "@/enums/orders/index";
import { REPAIR_INFO_CONTAINER_STYLE } from "../../data";

interface Props {
  repairOrderDetail: Recordable | null;
}

const emits = defineEmits(["update"]);

const message = useMessage();

const { showCheckResult, checkResultList, checkResultTitle } =
  useCheckResultModal();

const ownRepairOrderDetail = ref<Recordable>({});
const updateLoading = ref<boolean>(false);

const editImeiFlag = ref<boolean>(false);
const editPinFlag = ref<boolean>(false);

const showVariantModal = ref<boolean>(false);

const props = withDefaults(defineProps<Props>(), {
  repairOrderDetail: () => ({}),
});

const ownRepairInfo = ref<any>({});

const selectedCheckList = computed(() => {
  return checkResultList.value.filter((item: any) => item.result === "1");
});

const repairInfo = computed(() => {
  return get(ownRepairOrderDetail.value, "repair") || {};
});

const orderInfo = computed(() => {
  return get(ownRepairOrderDetail.value, "sales") || {};
});

watch(
  () => props.repairOrderDetail,
  (newVal) => {
    if (!isEmpty(newVal)) {
      init(newVal);
    }
  }
);

const handleEditVariant = () => {
  showVariantModal.value = true;
};

const handleClickAddQuestion = () => {
  showCheckResult.value = true;
};

const handleRemoveQuestion = async (questionItem: any) => {
  const { id } = questionItem;
  if (id) {
    let targetQuestion = checkResultList.value.find(
      (item: any) => item.id === id
    );
    if (targetQuestion) {
      updateLoading.value = true;
      try {
        const params = {
          id,
          result: "0",
        };
        await updateCheckResult(params);
        message.success("故障更新成功");
        targetQuestion.result = "0";
        emits("update");
      } finally {
        updateLoading.value = false;
      }
    }
  }
};

const handleConfirmAddQuestion = async (payload: any[]) => {
  const salesId = get(ownRepairOrderDetail.value, "sales.id") || "";
  if (!salesId) {
    message.error("订单id为空！");
    return;
  }
  checkResultList.value = cloneDeep(payload);
  showCheckResult.value = false;
  let checkedIds = [] as string[];
  let uncheckIds = [] as string[];
  payload.forEach((item: any) => {
    if (item.result === "1") {
      checkedIds.push(item.id);
    } else {
      uncheckIds.push(item.id);
    }
  });
  const params = {
    salesId,
    checkedIds,
    uncheckIds,
  };
  updateLoading.value = true;
  try {
    await updateCheckResultBatch(params);
    message.success("故障更新成功");
    emits("update");
  } finally {
    updateLoading.value = false;
  }
};

const handleClickEditSn = debounce(async function () {
  if (editImeiFlag.value) {
    // 保存
    try {
      updateLoading.value = true;
      const params = {
        id: ownRepairInfo.value.id,
        sn: ownRepairInfo.value.sn,
      };
      await updateSn(params);
      message.success("IMEI/SN更新成功");
      emits("update");
    } finally {
      updateLoading.value = false;
      editImeiFlag.value = false;
    }
  } else {
    editImeiFlag.value = true;
  }
}, 200);

const handleClickEditPin = debounce(async function () {
  if (editPinFlag.value) {
    // 保存
    try {
      updateLoading.value = true;
      const params = {
        id: ownRepairInfo.value.id,
        pin: ownRepairInfo.value.pin,
      };
      await updatePin(params);
      message.success("锁屏密码更新成功");
      emits("update");
    } finally {
      updateLoading.value = false;
      editPinFlag.value = false;
    }
  } else {
    editPinFlag.value = true;
  }
}, 200);

const handleChangeRepairStatus = debounce(async function (payload) {
  console.log(payload);
  const params = {
    id: ownRepairInfo.value.id,
    status: payload,
  };

  try {
    // 错误：应该先设置为 true 再执行异步操作
    updateLoading.value = true;  // 修正前是 false
    await changeRepairStatus(params);
    message.success("状态更新成功");
    emits("update");
  } finally {
    updateLoading.value = false;
  }
}, 200);

const handleUpdateVariant = async (variant: any) => {
  console.log(variant);
  const variantId = get(variant, "id") || "";
  if (variantId) {
    try {
      updateLoading.value = true;
      const params = {
        id: ownRepairInfo.value.id,
        variantId,
      };
      await updateRepairVariant(params);
      message.success("设备信息更新成功");
      showVariantModal.value = false;
      emits("update");
    } finally {
      updateLoading.value = false;
    }
  }
};

const init = (orderDetail: Recordable) => {
  ownRepairOrderDetail.value = cloneDeep(orderDetail);
  const checkList = get(orderDetail, "repairChecks") || [];
  checkResultTitle.value = "故障清单";
  checkResultList.value = cloneDeep(checkList);
  ownRepairInfo.value = cloneDeep(get(orderDetail, "repair") || {});
};
</script>
